import paramiko
import sys
import json
from flask import Flask, Response, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

def generate_output(host, username, password, script_path):
    try:
        # 建立SSH连接
        yield f"data: 正在连接到服务器 {host}...\n\n"
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, username=username, password=password)
        
        yield "data: SSH 连接已建立\n\n"
        
        # 创建交互式 shell
        channel = ssh.get_transport().open_session()
        channel.get_pty()
        channel.exec_command(f'python3 -u {script_path}')
        
        # 实时读取输出
        while True:
            if channel.exit_status_ready():
                break
                
            if channel.recv_ready():
                output = channel.recv(4096).decode('utf-8')
                for line in output.splitlines():
                    if line.strip():
                        yield f"data: {line}\n\n"
                        
            if channel.recv_stderr_ready():
                error = channel.recv_stderr(4096).decode('utf-8')
                for line in error.splitlines():
                    if line.strip():
                        yield f"data: 错误: {line}\n\n"
        
        yield "data: 脚本执行完毕\n\n"
        
    except Exception as e:
        yield f"data: 错误: {str(e)}\n\n"
    finally:
        if 'ssh' in locals():
            ssh.close()

@app.route('/execute')
def execute():
    host = request.args.get('host', '')
    username = request.args.get('username', '')
    password = request.args.get('password', '')
    script = request.args.get('script', '')
    
    return Response(
        generate_output(host, username, password, script),
        mimetype='text/event-stream'
    )

if __name__ == '__main__':
    app.run(debug=True, port=5000)
